package com.weiaibenpao.demo.chislim.ui.activity.discover;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.api.Url;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.db.preferences.LocationPreferences;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.ui.activity.running.StartRunActivity;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.LoadingDialogUtils;
import com.weiaibenpao.demo.chislim.utils.ShareUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MarathonWebActivity extends BaseActivity {


    Intent intent;
    @BindView(R.id.myWebView)
    WebView mWebView;
    @BindView(R.id.mid_text)
    TextView myTitle;
    private String marathonUrl;
    private LoadingDialogUtils.Builder dialog;

    private static final String APP_CACHE_DIRNAME = "/webcache";
    private ShareUtils shareUtils;
    private String urlContent;

    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_marathon_web;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        //url_record = PRODUCT_URL + marathon_detailUrl + UserBean.getUserBean().userId;
        urlContent = getIntent().getStringExtra(Constant.WEB_URL) + UserPreferences.getInstance().getInt(UserPreferences.USER_ID);
        marathonUrl = Url.BASE_URL + Url.SERVICE_SPORT + urlContent;
        Logger.e("marathonUrl:" + marathonUrl);
        shareUtils = new ShareUtils(this);
        initWebView();
    }

    public static void startSelf(Context context, String contentUrl) {
        Intent intent = new Intent(context, MarathonWebActivity.class);
        intent.putExtra(Constant.WEB_URL, contentUrl);
//        intent.putExtra(Constant.MARATHON_TITLE, titleName);
        context.startActivity(intent);
    }

    Map<String, String> map = new HashMap<String, String>();


    private void initWebView() {
        mWebView.loadUrl(marathonUrl);

        /**
         * WebSettings用来设置WebView的相关属性
         */
        WebSettings webSettings = mWebView.getSettings();
        //设置WebView支持JavaScript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        mWebView.addJavascriptInterface(new JS(), "android");

        dialog = new LoadingDialogUtils.Builder(this);
        dialog.setTitle("正在加载...").show();
        //第二种加载进度条的方法
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                if (newProgress>=99){
                    dialog.dismiss();
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                myTitle.setText(title);
            }
        });

        //第一种加载进度条的方法
        mWebView.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                mWebView.loadUrl(url);
//                return true;
                return false;
            }


        } );


        mWebView.loadUrl(marathonUrl);
//        mWebView.loadUrl("https://www.baidu.com/");
//        Log.e("HWebView","load url is "+urlStr);

    }


    /**
     * 重写onKeyDown方法用于在WebView中点击回退键时,返回url的上一层,
     * 否则会直接跳出WebView
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();    //返回上一页
            return true;
        } else {
            finish();      //某些Android版本不生效        System.exit(0);    //某些Android版本不生效
        }
        return super.onKeyDown(keyCode, event);
    }


    @OnClick({R.id.left_image,R.id.right_image})
    public void onViewClicked(View v) {
        switch (v.getId()){
            case R.id.left_image:
                finish();
                break;
            case R.id.right_image:
              checkPerMissions();
                break;
        }
    }

    @Override
    protected void startDo() {
        super.startDo();
        share();
    }

    class JS {

        @JavascriptInterface
        public void go() {

            //todo 前往马拉松跑步
            //p userId=43&marathonId=22&marathonId=21&sportType=232&matchStartTime=522
            // subString(p);
            String latitude = LocationPreferences.getInstance().getLocationLatitude();
            String longitude = LocationPreferences.getInstance().getLocationLongitude();
            StartRunActivity.openActivity(MarathonWebActivity.this, 1, "", 0, "", 0, null, Float.parseFloat(latitude), Float.parseFloat(longitude));
            finish();
        }
    }

    private void share() {
        shareUtils.share(urlContent,myTitle.getText().toString() );
//        share.shareLink(url_record,"\"" + getIntent().getStringExtra(MARATHON_TITLE) + "\"，一起来报名吧！","东极圈，跑出不一样的自己；启迈斯为您助跑！");
    }

    /**
     * 解析前端返回的数据
     */
    public void subString(String str) {
        String[] strs = str.split("&");
        for (int i = 0; i < strs.length; i++) {

            String[] strs_value = strs[i].split("=");
            if (strs_value.length > 1) {
                map.put(strs_value[0], strs_value[1]);
            }
        }
    }
}
